const jwt = require('jsonwebtoken');
const { query } = require('../config/database');
const configService = require('../services/configService');

// JWT认证中间件
const authenticateToken = async (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ message: '访问令牌缺失' });
  }

  try {
    const jwtConfig = await configService.getJWTConfig();
    const decoded = jwt.verify(token, jwtConfig.secret);
    const user = await query('SELECT id, username, email, is_active FROM users WHERE id = ?', [decoded.userId]);
    
    if (!user.length || !user[0].is_active) {
      return res.status(401).json({ message: '用户不存在或已被禁用' });
    }

    req.user = user[0];
    next();
  } catch (error) {
    return res.status(403).json({ message: '访问令牌无效' });
  }
};

// 管理员权限中间件
const requireAdmin = async (req, res, next) => {
  try {
    // 检查用户是否为管理员
    const user = await query('SELECT id, username, email, is_admin FROM users WHERE id = ?', [req.user.id]);
    
    if (!user.length || !user[0].is_admin) {
      return res.status(403).json({ message: '需要管理员权限' });
    }

    next();
  } catch (error) {
    console.error('管理员权限检查失败:', error);
    return res.status(500).json({ message: '权限检查失败' });
  }
};

module.exports = {
  authenticateToken,
  requireAdmin
};